#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/12 20:35
# @Author : cjw
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, BigInteger, Date, DateTime, ForeignKey, func

from coronavirus.database import Base


class City(Base):
    """城市表"""
    __tablename__ = 'city'  # 数据表的表名

    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment='主键')
    province = Column(String(50), unique=True, nullable=False, comment='省/直辖市')
    country = Column(String(50), nullable=False, comment='国家')
    country_code = Column(String(50), nullable=False, comment='国家代码')
    country_population = Column(BigInteger, nullable=False, comment='人口')
    # Data：是关联的类名，back_populates：来指定反向访问的属性名
    data = relationship('Data', back_populates='city')

    # func是个函数对象，函数下有可调用的方法
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='更新时间')

    # 数据排序，默认是正序，倒叙加上.desc()方法，示例：country_code.desc()
    # __mapper_args__ = {"order_by": country_code}

    def __repr__(self):
        return f'{self.country}_{self.province}'


class Data(Base):
    """数据表"""
    __tablename__ = 'data'

    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment='主键')
    # ForeignKey里的字符串格式不是类名.属性名，而是表名.字段名
    city_id = Column(Integer, ForeignKey('city.id'), comment='所属省/直辖市')
    date = Column(Date, nullable=False, comment='数据日期')
    confirmed = Column(Integer, default=0, nullable=False, comment='确诊数量')
    deaths = Column(Integer, default=0, nullable=False, comment='死亡数量')
    recovered = Column(Integer, default=0, nullable=False, comment='痊愈数量')
    city = relationship('City', back_populates='data')

    # func是个函数对象，函数下有可调用的方法
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='更新时间')

    # __mapper_args__ = {"order_by": date.desc()}

    def __repr__(self):
        return f'{repr(self.date)}: 确诊{self.confirmed}例'
